﻿namespace CatFax.Service.WebRole
{
    using CatFax.Entities;
    using Microsoft.Samples.ServiceHosting.StorageClient;

    /// <summary>
    /// Used for figuring out the indexes for rows
    /// </summary>
    public class AuditRowIndexer
    {
        /// <summary>
        /// Find the index row and returns LastSeq+1
        /// </summary>
        /// <param name="partitionKey">
        /// The partition key.
        /// </param>
        /// <param name="rowKey">
        /// The row key.
        /// </param>
        /// <returns>
        /// Next sequence number
        /// </returns>
        public static int GetNextSeqForRow(string partitionKey, string rowKey)
        {
            StorageAccountInfo accountInfo = StorageAccountInfo.GetAccountInfoFromConfiguration("TableStorageEndpoint");
            AuditRowIndexEntityDataServiceContext auditRowIndexEntityDataServiceContext = new AuditRowIndexEntityDataServiceContext(accountInfo);
            if (auditRowIndexEntityDataServiceContext.Exists(rowKey))
            {
                return auditRowIndexEntityDataServiceContext.NextSeqForRow(rowKey, partitionKey);
            }
            else
            {
                auditRowIndexEntityDataServiceContext.AddAuditRowIndexEntity(rowKey, 1, partitionKey);
                return 1;
            }
        }
    }
}
